package cn.com.ghy.android.widget.plan;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.MyWayBean;
import cn.com.ghy.android.bean.VisitPlanBean;
import cn.com.ghy.android.bean.VisitPlanWorkTypeBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.PlanOpeService;
import cn.com.ghy.android.style.MenuTabContent;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.util.CommonUtil;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;
import cn.com.ghy.android.widget.way.MyWay;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:下月拜访计划
 * @author wuz  @date 2011-5-25 08:16:53
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class VisitPlan extends Activity {

	private TextView labTxtMonth = null;
	private TextView labTxtVisitPlanStatus = null;
	private ListView listVisitPlanList = null;
	private Intent intent = null;
	private Bundle bundle = null;
	private ProgressDialog progressDialog = null;
	private ImageButton btnBack = null;
	private ImageButton btnList = null;

	private MenuTabContent.MenuBodyAdapter bodyAdapter = null;
	private MenuTabContent tabMenu;
	private View appToolBar = null;

	List<VisitPlanWorkTypeBean> visitPlanWorkTypeList = null;
	List<MyWayBean> myWayList = null;
	private String[] weekDays = { "日", "一", "二", "三", "四", "五", "六" };
	private String visitPlanStatus = "";
	private List<VisitPlanBean> visitPlanList = null;
	private List<VisitPlanBean> curPlanLast = null;
	private String curPlanStatus = "";
	private String monthid = null;
	private Map<String, String> visitPlanStatusMap = null;
	private LoginInfoBean loginInfo = null;

	private VisitPlanListAdapter visitPlanListAdapter = null;

	private HttpThread httpThread = null;

	private DisposeException disposeException = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.visit_plan);
		getSession();
		setToolBar();
		setMenu();
		findView();
		init();
		addListener();
	}

	@SuppressWarnings("unchecked")
	private void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfo = ((ComStaticApp) this.getApplication()).getLoginInfo();
		bundle = this.getIntent().getExtras();
		visitPlanWorkTypeList = (List<VisitPlanWorkTypeBean>) bundle
				.getSerializable("visitPlanWorkTypeList");
		myWayList = (List<MyWayBean>) bundle.getSerializable("myWayList");
		visitPlanStatus = bundle.getString("visitPlanStatus");
		visitPlanList = (List<VisitPlanBean>) bundle.getSerializable("visitPlanList");
		monthid = bundle.getString("monthid");
		if (null == visitPlanStatus || "".equals(visitPlanStatus)) {
			Toast.makeText(VisitPlan.this, "程序出错,请与管理员联系!", Toast.LENGTH_LONG).show();
			VisitPlan.this.finish();
		}
		if (null == monthid || "".equals(monthid)) {
			Toast.makeText(VisitPlan.this, "程序出错,请与管理员联系!", Toast.LENGTH_LONG).show();
			VisitPlan.this.finish();
		}

		visitPlanStatusMap = new HashMap<String, String>();
		visitPlanStatusMap.put(CommonStatic.visitPlan_Y, "通过审核");
		visitPlanStatusMap.put(CommonStatic.visitPlan_X, "未通过审核");
		visitPlanStatusMap.put(CommonStatic.visitPlan_A, "正在审核中");
		visitPlanStatusMap.put(CommonStatic.visitPlan_W, "保存状态");
		visitPlanStatusMap.put(CommonStatic.visitPlan_N, "未填写计划");
	}

	private void setToolBar() {
		appToolBar = findViewById(R.id.appToolBar);
		btnList = (ImageButton) appToolBar.findViewById(R.id.btnList);
		btnBack = (ImageButton) appToolBar.findViewById(R.id.btnBack);
	}

	private void findView() {
		appToolBar = (RelativeLayout) findViewById(R.id.appToolBar);

		labTxtMonth = (TextView) this.findViewById(R.id.labTxtMonth);
		labTxtVisitPlanStatus = (TextView) this.findViewById(R.id.labTxtVisitPlanStatus);

		listVisitPlanList = (ListView) this.findViewById(R.id.listVisitPlanList);
	}

	private void init() {

		if (null == visitPlanList || visitPlanList.size() == 0) {
			Calendar c = Calendar.getInstance();
			c.set(Integer.parseInt(monthid.substring(0, 4)),
					Integer.parseInt(monthid.substring(4, 6)) - 1, 1);
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int endDay = c.getActualMaximum(Calendar.DATE);

			visitPlanList = new ArrayList<VisitPlanBean>();
			int dayOfWeek = 0;
			for (int i = 1; i <= endDay; i++) {
				c.set(year, month, i);
				dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
				VisitPlanBean visitPlanBean = new VisitPlanBean(i, weekDays[dayOfWeek],
						new MyWayBean(), new VisitPlanWorkTypeBean());
				visitPlanList.add(visitPlanBean);
			}
			visitPlanListAdapter = new VisitPlanListAdapter(VisitPlan.this, visitPlanList);
			listVisitPlanList.setAdapter(visitPlanListAdapter);
		} else {
			visitPlanListAdapter = new VisitPlanListAdapter(VisitPlan.this, visitPlanList);
			listVisitPlanList.setAdapter(visitPlanListAdapter);
		}
		labTxtMonth.setText(monthid);
		labTxtVisitPlanStatus.setText(visitPlanStatusMap.get(visitPlanStatus));
	}

	public void addListener() {
		if (visitPlanStatus.equals(CommonStatic.visitPlan_Y)
				|| visitPlanStatus.equals(CommonStatic.visitPlan_A)) {

		} else {
			listVisitPlanList.setOnItemClickListener(listVisitPlanLis);
		}

		btnList.setOnClickListener(imgBtnListener);
		btnBack.setOnClickListener(imgBtnListener);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case CommonStatic.INTENT_REQUEST_CODE :
				if (resultCode == RESULT_OK) {
					bundle = data.getExtras();
					VisitPlanBean resultBean = (VisitPlanBean) bundle
							.getSerializable("visitPlanBean");
					if ("-1".equals(resultBean.getMyWayBean().getWayid())) {
						resultBean.setMyWayBean(new MyWayBean());
					}
					if (-1 == resultBean.getVisitPlanWorkTypeBean().getWorkTypeId()) {
						resultBean.setVisitPlanWorkTypeBean(new VisitPlanWorkTypeBean());
					}
					int position = -1;
					position = bundle.getInt("position");
					if (position != -1) {
						visitPlanListAdapter.modify(position, resultBean);
					}
				}
				break;
			default :
				break;
		}
	}

	private View.OnClickListener imgBtnListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.btnList :
					openOptionsMenu();
					break;
				case R.id.btnBack :
					exit();
					break;
			}

		}
	};

	private OnItemClickListener listVisitPlanLis = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			bundle = new Bundle();
			bundle.putSerializable("visitPlanBean",
					(VisitPlanBean) parent.getItemAtPosition(position));
			bundle.putSerializable("myWayList", (Serializable) myWayList);
			bundle.putSerializable("visitPlanWorkTypeList", (Serializable) visitPlanWorkTypeList);
			bundle.putInt("position", position);
			intent = new Intent(VisitPlan.this, VisitPlanPop.class);
			intent.putExtras(bundle);
			VisitPlan.this.startActivityForResult(intent, CommonStatic.INTENT_REQUEST_CODE);

		}

	};

	private class VisitPlanListAdapter extends BaseAdapter {

		private Context context = null;
		private List<VisitPlanBean> list = null;

		public VisitPlanListAdapter(Context context, List<VisitPlanBean> list) {
			this.context = context;
			this.list = list;
		}

		public int getCount() {
			return list.size();
		}

		public VisitPlanBean getItem(int position) {
			return list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(inflater);
			LinearLayout linearLayout = (LinearLayout) layoutInflater.inflate(
					R.layout.visit_plan_lay, null);

			VisitPlanBean bean = list.get(position);
			TextView tv = (TextView) linearLayout.findViewById(R.id.labTxtDay);
			tv.setText(bean.getVsdate() + "");
			tv = (TextView) linearLayout.findViewById(R.id.labTxtWeek);
			tv.setText(bean.getWk());
			tv = (TextView) linearLayout.findViewById(R.id.labTxtWay);
			tv.setText(null == bean.getMyWayBean().getWayname() ? "" : bean.getMyWayBean()
					.getWayname());
			tv = (TextView) linearLayout.findViewById(R.id.labTxtWorkType);
			tv.setText(null == bean.getVisitPlanWorkTypeBean().getWorkTypeName() ? "" : bean
					.getVisitPlanWorkTypeBean().getWorkTypeName());

			return linearLayout;
		}

		public void modify(int position, VisitPlanBean bean) {
			if (position < 0)
				return;
			list.remove(position);
			list.add(position, bean);
			notifyDataSetChanged();
		}

	}

	private class HttpThread extends Thread {
		private Handler handle = null;
		private int flag = -1;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		public void doStart(int flag) {
			this.flag = flag;
			progressDialog = new ProgressDialog(VisitPlan.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Message message = null;
			String result = null;
			PlanOpeService planOpeService = new PlanOpeService();
			;

			try {
				switch (flag) {
					case R.drawable.menu_submit :
						result = planOpeService.SetPlan(loginInfo, monthid, visitPlanList);
						if (null != result && !"".equals(result)) {
							if ("OK".equals(result)) {
								result = planOpeService.SendPlan(loginInfo, monthid);
								if (null != result && !"".equals(result)) {
									progressDialog.dismiss();
									message = handle.obtainMessage();
									bundle = new Bundle();
									message.what = CommonStatic.STATE_NORMAL;
									bundle.putString("result", result);
									bundle.putInt("flag", flag);
									message.setData(bundle);
									handle.sendMessage(message);
								} else {
									progressDialog.dismiss();
									bundle = new Bundle();
									message = handle.obtainMessage();
									message.what = CommonStatic.STATE_NORMAL_NULL;
									bundle.putInt("flag", flag);
									message.setData(bundle);
									handle.sendMessage(message);
								}
							} else {
								progressDialog.dismiss();
								message = handle.obtainMessage();
								bundle = new Bundle();
								message.what = CommonStatic.STATE_NORMAL;
								bundle.putString("result", result);
								bundle.putInt("flag", flag);
								message.setData(bundle);
								handle.sendMessage(message);
							}
						} else {
							progressDialog.dismiss();
							bundle = new Bundle();
							message = handle.obtainMessage();
							message.what = CommonStatic.STATE_NORMAL_NULL;
							bundle.putInt("flag", flag);
							message.setData(bundle);
							handle.sendMessage(message);
						}
						break;
					case R.drawable.menu_save :
						result = planOpeService.SetPlan(loginInfo, monthid, visitPlanList);
						if (null != result && !"".equals(result)) {
							progressDialog.dismiss();
							message = handle.obtainMessage();
							bundle = new Bundle();
							message.what = CommonStatic.STATE_NORMAL;
							bundle.putString("result", result);
							bundle.putInt("flag", flag);
							message.setData(bundle);
							handle.sendMessage(message);
						} else {
							progressDialog.dismiss();
							bundle = new Bundle();
							message = handle.obtainMessage();
							message.what = CommonStatic.STATE_NORMAL_NULL;
							bundle.putInt("flag", flag);
							message.setData(bundle);
							handle.sendMessage(message);
						}
						break;
					case R.drawable.menu_current_plan :
						String curMonthid = CommonUtil.lastMonth(monthid);
						curPlanStatus = planOpeService.GetPlanState(loginInfo, curMonthid);
						message = handle.obtainMessage();
						message.what = CommonStatic.STATE_NORMAL;
						bundle = new Bundle();
						if (!CommonStatic.visitPlan_N.equals(curPlanStatus)) {
							curPlanLast = planOpeService.GetPlan(loginInfo, curMonthid);
							bundle.putSerializable("curPlanLast", (Serializable) curPlanLast);
						}
						progressDialog.dismiss();
						bundle.putString("curPlanStatus", curPlanStatus);
						bundle.putString("curMonthid", curMonthid);
						bundle.putInt("flag", flag);
						message.setData(bundle);
						handle.sendMessage(message);
						break;
					default :
						progressDialog.dismiss();
						bundle = new Bundle();
						message = handle.obtainMessage();
						message.what = CommonStatic.STATE_NORMAL_NULL;
						bundle.putInt("flag", flag);
						message.setData(bundle);
						handle.sendMessage(message);
						break;
				}
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
		}
	}

	private Handler handler = new Handler() {
		private int flag = -1;

		public void handleMessage(Message m) {
			flag = m.getData().getInt("flag");
			;
			String result = m.getData().getString("result");
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					switch (flag) {
						case R.drawable.menu_submit :
							if ("OK".equals(result)) {
								new AlertDialog.Builder(VisitPlan.this)
										.setTitle("提示信息")
										.setMessage("提交下月拜访计划成功!")
										.setPositiveButton("确定",
												new DialogInterface.OnClickListener() {
													public void onClick(DialogInterface dlg,
															int sumthin) {
														VisitPlan.this.finish();
													}
												}).show();
							} else {
								new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
										.setMessage(result).setNeutralButton("关闭", null).show();
							}
							break;
						case R.drawable.menu_save :
							if ("OK".equals(result)) {
								new AlertDialog.Builder(VisitPlan.this)
										.setTitle("提示信息")
										.setMessage("保存下月拜访计划成功, 是否关闭此页面!")
										.setPositiveButton("确定",
												new DialogInterface.OnClickListener() {
													public void onClick(DialogInterface dlg,
															int sumthin) {
														VisitPlan.this.finish();
													}
												}).setNeutralButton("取消", null).show();
							} else {
								new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
										.setMessage(result).setNeutralButton("关闭", null).show();
							}
							break;
						case R.drawable.menu_current_plan :
							String curPlanStatus = (String) m.getData().getString("curPlanStatus");
							String curMonthid = (String) m.getData().getString("curMonthid");
							if (CommonStatic.visitPlan_N.equals(curPlanStatus)) {
								new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
										.setMessage("没有制定" + curMonthid + "月的拜访计划!")
										.setPositiveButton("确定", null).show();
							} else {
								@SuppressWarnings("unchecked")
								List<VisitPlanBean> curPlanLast = (List<VisitPlanBean>) m.getData()
										.getSerializable("curPlanLast");

								bundle = new Bundle();
								bundle.putSerializable("curPlanLast", (Serializable) curPlanLast);
								bundle.putString("curPlanStatus", curPlanStatus);
								bundle.putString("curMonthid", curMonthid);
								intent = new Intent(VisitPlan.this, CurVisitPlan.class);
								intent.putExtras(bundle);
								VisitPlan.this.startActivity(intent);
							}
							break;
						default :
							new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
									.setMessage("程序处理异常,请联系管理员!").setNeutralButton("关闭", null)
									.show();
							break;
					}
					break;
				case CommonStatic.STATE_NORMAL_NULL :
					switch (flag) {
						case R.drawable.menu_submit :
							new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
									.setMessage("提交下月拜访出错,请联系管理员!").setNeutralButton("关闭", null)
									.show();
							break;
						case R.drawable.menu_save :
							new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
									.setMessage("保存下月拜访出错,请联系管理员!").setNeutralButton("关闭", null)
									.show();
							break;
						default :
							new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
									.setMessage("程序出现异常,请联系管理员!").setNeutralButton("关闭", null)
									.show();
							break;
					}
					break;
			}
		}
	};

	private void setMenu() {
		bodyAdapter = new MenuTabContent.MenuBodyAdapter(this, new String[] { "提交审核", "保存计划",
				"我的路线", "本月计划" }, new int[] { R.drawable.menu_submit, R.drawable.menu_save,
				R.drawable.menu_myway, R.drawable.menu_current_plan }, 13, getResources().getColor(
				R.color.white));

		tabMenu = new MenuTabContent(this, new BodyClickEvent(), getResources().getColor(
				R.color.MenuBackGroundColor), R.style.PopupAnimation);

		tabMenu.update();
		tabMenu.SetBodyAdapter(bodyAdapter);
	}

	private class BodyClickEvent implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			tabMenu.SetBodySelect(position, Color.GRAY);
			switch (position) {
				case 0 :
					if (visitPlanStatus.equals(CommonStatic.visitPlan_Y)
							|| visitPlanStatus.equals(CommonStatic.visitPlan_A)) {
						Toast.makeText(
								VisitPlan.this,
								monthid + "计划," + visitPlanStatusMap.get(visitPlanStatus)
										+ ",不能重复提交!", Toast.LENGTH_LONG).show();
						break;
					}
					new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息")
							.setMessage("确认提交下月拜访计划?")
							.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dlg, int sumthin) {
									httpThread = new HttpThread(handler);
									httpThread.doStart(R.drawable.menu_submit);
								}
							}).setNeutralButton("取消", null).show();
					break;
				case 1 :
					if (visitPlanStatus.equals(CommonStatic.visitPlan_Y)
							|| visitPlanStatus.equals(CommonStatic.visitPlan_A)) {
						Toast.makeText(
								VisitPlan.this,
								monthid + "计划," + visitPlanStatusMap.get(visitPlanStatus)
										+ ",不能重复保存!", Toast.LENGTH_LONG).show();
						break;
					}
					httpThread = new HttpThread(handler);
					httpThread.doStart(R.drawable.menu_save);
					break;
				case 2 :
					bundle = new Bundle();
					bundle.putSerializable("myWayList", (Serializable) myWayList);
					intent = new Intent(VisitPlan.this, MyWay.class);
					intent.putExtras(bundle);
					VisitPlan.this.startActivity(intent);
					break;
				case 3 :
					httpThread = new HttpThread(handler);
					httpThread.doStart(R.drawable.menu_current_plan);
					break;
				default :
					break;
			}
			if (null != tabMenu) {
				if (tabMenu.isShowing()) {
					tabMenu.dismiss();
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (tabMenu != null) {
			if (tabMenu.isShowing()) {
				tabMenu.dismiss();
			} else {
				int toolBarHeight = appToolBar.getHeight();
				tabMenu.showAtLocation(findViewById(R.id.appToolBar), Gravity.BOTTOM, 0,
						toolBarHeight);
			}
		}
		return false;
	}

	private void exit() {
		new AlertDialog.Builder(VisitPlan.this).setTitle("提示信息").setMessage("确定要退出下月拜访计划?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						VisitPlan.this.finish();
					}

				}).setNegativeButton("取消", null).show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
		}
		return true;
	}
}
